<template>
  <div class="player-container">
    <video-player
        :options="playerOptions"
        @ready="onPlayerReady"
    />
  </div>
</template>

<script setup lang="ts">
import {reactive} from 'vue';
import {VideoPlayer} from '@videojs-player/vue';
import 'video.js/dist/video-js.css';
import '@videojs/themes/dist/fantasy/index.css';
import type {VideoJsPlayerOptions} from "video.js";

defineOptions({
  name: 'VuePlayer'
})

const props = defineProps({
  autoPlay: {
    type: Boolean,
    default: false
  },
  videoSrc: {
    type: String,
    default: '',
  },
  videoType: {
    type: String,
    default: 'video/mp4',
  }
})

// 播放器配置
const playerOptions = reactive<VideoJsPlayerOptions>({
  autoplay: props.autoPlay,
  muted: true,
  controls: true,
  fluid: true,
  controlBar: {
    children: [
      'playToggle',
      'volumePanel',
      'currentTimeDisplay',
      'progressControl',
      'remainingTimeDisplay',
      'qualitySelector', // 内置分辨率选择器
      'fullscreenToggle'
    ]
  },
  html5: {
    vhs: {
      overrideNative: true, // 强制使用 video.js 处理
      enableLowInitialPlaylist: true,
      experimentalBufferBasedABR: true
    }
  },
  sources: [{
    src: props.videoSrc,
    type: props.videoType
  }]
});

// 初始化分辨率切换功能
const initQualitySelector = (player: VideoPlayer) => {
  if (!player.qualityLevels) return;

  const qualityLevels = player.qualityLevels();
  const validLevels = qualityLevels.levels_.filter(level => level.height);

  // 创建分辨率菜单项
  const menuItems = validLevels.map((level, index) => ({
    label: `${level.height}p`,
    selected: index === qualityLevels.selectedIndex,
    callback: () => {
      qualityLevels.selectedIndex = index;
    }
  }));

  // 添加分辨率选择按钮
  player.getChild('controlBar')?.addChild('QualitySelector', {
    title: 'Quality',
    items: menuItems
  });
};

// 播放器就绪回调
const onPlayerReady = (player: VideoPlayer) => {
};
</script>

<style>
.player-container{

}
/* 自定义分辨率选择器样式 */
.vjs-quality-selector .vjs-menu-button {
  margin: 0 5px;
}

.vjs-quality-selector .vjs-menu {
  width: auto;
  left: -2em;
}

.vjs-quality-selector .vjs-menu-content {
  min-width: 120px;
}
</style>